2
https://raw.githubusercontent.com/aayush-grover/SoundCloud-Rest-Api/master/musichoster-service/src/main/java/com/upgrad/musichoster/service/business/AuthenticationServiceImpl.java
package com.upgrad.musichoster.service.business;

import com.upgrad.musichoster.service.dao.UserDao;
import com.upgrad.musichoster.service.entity.UserAuthTokenEntity;
import com.upgrad.musichoster.service.entity.UserEntity;
import com.upgrad.musichoster.service.exception.AuthenticationFailedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZonedDateTime;

@Service
public class AuthenticationServiceImpl implements AuthenticationService {

	@Autowired
	private UserDao userDao;

	@Autowired
	private PasswordCryptographyProvider CryptographyProvider;


	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public UserAuthTokenEntity authenticate(String username, String password)
			throws AuthenticationFailedException {
		UserEntity userEntity = userDao.getUserByEmail(username);
		if (userEntity == null) {
			throw new AuthenticationFailedException("ATH-001", "User with email not found");
		}

		final String encryptedPassword = CryptographyProvider.encrypt(password, userEntity.getSalt());
		if (encryptedPassword.equals(userEntity.getPassword())) {
			JwtTokenProvider jwtTokenProvider = new JwtTokenProvider(encryptedPassword);
			UserAuthTokenEntity userAuthTokenEntity = new UserAuthTokenEntity();
			userAuthTokenEntity.setUser(userEntity);
			final ZonedDateTime now = ZonedDateTime.now();
			final ZonedDateTime expiresAt = now.plusHours(8);

			userAuthTokenEntity.setAccessToken(jwtTokenProvider.generateToken(userEntity.getUuid(), now, expiresAt));

			userAuthTokenEntity.setLoginAt(now);
			userAuthTokenEntity.setExpiresAt(expiresAt);

			userDao.createAuthToken(userAuthTokenEntity);

			userDao.updateUser(userEntity);
			userEntity.setLastLoginAt(now);
			return userAuthTokenEntity;
		} else {
			throw new AuthenticationFailedException("ATH-002", "Password failed");
		}
	}
}
